﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BinaryTree
{
    class Tree
    {
        private static int key = 0;
        private static Node root = new Node();

        public class Node
        {
            public int value = -1;
            public int key = -1;
            public Node leftNode = null;
            public Node rightNode = null;
        }

        public Node create(int[] values)
        {
            int middle = values.Length - (values.Length / 2);
            
            Console.WriteLine("MIDDLE: " + values[middle - 1]);
            Insert(values[middle - 1], key, ref root);
            key++;

            int[] leftArray = new int[middle - 1];
            int[] rightArray = new int[values.Length - (middle)];

            if (leftArray.Length > 0)
            {
                for (int i = 0; i < leftArray.Length; i++)
                    leftArray[i] = values[i];

                create(leftArray);
            }

            if (middle < values.Length)
            {
                int count = 0;

                for (int i = middle; i < values.Length; i++)
                {
                    rightArray[count] = values[i];
                    count++;
                }

                create(rightArray);
            }

            return root;
        }

        private void Insert(int value, int key, ref Node node)
        {
            if (node.value == -1)
            {
                node.value = value;
                node.key = key;
                return;
            }

            if (value < node.value)
            {
                if (node.leftNode == null)
                {
                    node.leftNode = new Node();
                    node.leftNode.value = value;
                    node.leftNode.key = key;
                }
                else
                    Insert(value, key, ref node.leftNode);
            }
            else
            {
                if (node.rightNode == null)
                {
                    node.rightNode = new Node();
                    node.rightNode.value = value;
                    node.rightNode.key = key;
                }
                else
                {
                    Insert(value, key, ref node.rightNode);
                }
            }
        }
    }
}
